package com.dao;

import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

/**
 * version 1.0.0
 * dao
 * @author KKW
 * @date 2016/12/7.
 */
@Repository("baseDao")
public class BaseDao <T>{
    @Autowired
    private SessionFactory sessionFactory;

    /**
     * 需要和事务同步才能执行这个方法，所以hibernate需要添加事务
     * @return
     */
    public Session getCurrentSession(){
        return this.sessionFactory.getCurrentSession();
    }

    /**
     * 保存一个持久化对象
     * @param o
     */
    public void save(T o) {
        this.getCurrentSession().save(o);
    }

    public void update(T o) {
        this.getCurrentSession().update(o);
    }

    public void delete(T o) {
        this.getCurrentSession().delete(o);
    }

    /**
     * 合并一个持久化对象
     * @param o
     */
    public void merge(T o){
        this.getCurrentSession().merge(o);
    }

    public void saveOrUpadat(T o) {
        this.getCurrentSession().saveOrUpdate(o);
    }

    public T get(String hql, Object... param) {
        Query query=this.getCurrentSession().createQuery(hql);
        if(param!=null&&param.length>0) {
            for (int i = 0; i < param.length; i++) {
                query.setParameter(i, param[i]);
            }
        }
        return (T)query.uniqueResult();
    }

    public T get(Class<T> c, Serializable id) {
        return (T)this.getCurrentSession().get(c,id);
    }

    public List<T> search(String hql, Object... param) {
        Query query=this.getCurrentSession().createQuery(hql);
        if(param!=null&&param.length>0) {
            for (int i = 0; i < param.length; i++) {
                query.setParameter(i, param[i]);
            }
        }
        return query.list();
    }

    public List<T> searchWithPage(String hql, int page, int rows, Object... param) {
        Query query=this.getCurrentSession().createQuery(hql);
        if(param!=null&&param.length>0) {
            for (int i = 0; i < param.length; i++) {
                query.setParameter(i, param[i]);
            }
        }
        return query.setFirstResult((page-1)*rows).setMaxResults(rows).list();
    }

    public Object count(String hql, Object... param) {
        Query query=this.getCurrentSession().createQuery(hql);
        if(param!=null&&param.length>0) {
            for (int i = 0; i < param.length; i++) {
                query.setParameter(i, param[i]);
            }
        }
        return query.uniqueResult();
    }

    public int executeHql(String hql,Object... param){
        Query query=this.getCurrentSession().createQuery(hql);
        if(param!=null&&param.length>0) {
            for (int i = 0; i < param.length; i++) {
                query.setParameter(i, param[i]);
            }
        }
        return query.executeUpdate();
    }
}
